package org.example.backend.utils;


import com.mysql.cj.util.StringUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.example.backend.bean.UserBase;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author 啊昌
 * @date 2025/7/19 12:01
 * JwtUtil jwt工具类
 */
@Slf4j
@Component
public class JwtUtils {

	@Value("${jwt.secret}")
	private String secret;

	@Value("${jwt.expiration}")
	private Long expiration;


	public Long getUserIdFromToken() {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
				.currentRequestAttributes()).getRequest();
		String token = request.getHeader("Authorization");
		Claims claims = null;
		if(!StringUtils.isNullOrEmpty(token)) {
			claims = parseToken(token);
		}
		return Long.parseLong(claims.getSubject());
	}


	/**
	 * 生成token
	 * @param userId 用户id
	 * @return token字符串
	 */
	public String generateToken(Long userId) {
		Date now = new Date();
		return Jwts.builder()
				.setSubject(String.valueOf(userId))
				.setIssuedAt(now)
				.setExpiration(new Date(now.getTime() + expiration))
				.signWith(SignatureAlgorithm.HS256, secret)
				.compact();
	}

	public String generateToken(UserBase userBase) {
		Date now = new Date();
		return Jwts.builder()
				.setSubject(String.valueOf(userBase.getUserId()))
				.setSubject(String.valueOf(userBase.getUser_type()))
				.setIssuedAt(now)
				.setExpiration(new Date(now.getTime() + expiration))
				.signWith(SignatureAlgorithm.HS256, secret)
				.compact();
	}


	/**
	 * 验证JWT令牌的有效性。
	 *
	 * @param token JWT令牌字符串
	 * @return 如果令牌有效，则返回true；否则返回false
	 * @throws Exception 如果在验证过程中发生任何异常，则抛出该异常
	 */
	public boolean validateToken(String token) {
		try {
			Jwts.parser().setSigningKey(secret).parseClaimsJws(token);
			return true;
		} catch (Exception e) {
			log.error("Token validation failed: {}", e.getMessage());
			return false;
		}
	}


	/**
	 * 解析JWT令牌并返回Claims对象
	 *
	 * @param token JWT令牌字符串
	 * @return 解析后的Claims对象
	 */
	public Claims parseToken(String token) {
		return Jwts.parser()
				.setSigningKey(secret)
				.parseClaimsJws(token)
				.getBody();
	}


//	获取用户名
	public String getUsernameFromToken(String token) {
		Claims claims = parseToken(token);
		return claims.get("username", String.class);
	}

	public Long getUserIdFromToken(String token) {
		Claims claims = parseToken(token);
		return Long.parseLong(claims.getSubject());
	}

	public Integer getRoleFromToken(String token) {
		Claims claims = parseToken(token);
		return claims.get("role", Integer.class);
	}
}
